<template>
  <div class="grade-container">
    <div class="table-operations">
      <a-space>
        <a-select
          v-model:value="filterStudentId"
          placeholder="选择学生"
          style="width: 200px"
          allowClear
          @change="handleFilterChange"
          :loading="studentsLoading"
        >
          <a-select-option v-for="item in students" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
        <a-select
          v-model:value="filterSubjectId"
          placeholder="选择科目"
          style="width: 200px"
          allowClear
          @change="handleFilterChange"
          :loading="subjectsLoading"
        >
          <a-select-option v-for="item in subjects" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
        <a-button type="primary" @click="showModal()">
          <template #icon><plus-outlined /></template>
          添加成绩
        </a-button>
      </a-space>
    </div>

    <a-table :columns="columns" :data-source="filteredGrades" :loading="loading" row-key="id">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'studentName'">
          {{ getStudentName(record.studentId) }}
        </template>
        <template v-else-if="column.key === 'subjectName'">
          {{ getSubjectName(record.subjectId) }}
        </template>
        <template v-else-if="column.key === 'score'">
          <a-tag :color="getScoreColor(record.score)">
            {{ record.score }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a @click="showModal(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这条成绩记录吗？"
              @confirm="handleDelete(record.id)"
            >
              <a>删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <a-modal
      v-model:visible="modalVisible"
      :title="currentRecord ? '编辑成绩' : '添加成绩'"
      @ok="handleOk"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="学生" name="studentId">
          <a-select v-model:value="formState.studentId" :loading="studentsLoading">
            <a-select-option v-for="item in students" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="科目" name="subjectId">
          <a-select v-model:value="formState.subjectId" :loading="subjectsLoading">
            <a-select-option v-for="item in subjects" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="分数" name="score">
          <a-input-number v-model:value="formState.score" :min="0" :max="100" style="width: 100%" />
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-textarea v-model:value="formState.remark" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import request from '../../utils/request'

const API_URL = '/grades'
const STUDENTS_API_URL = '/students'
const SUBJECTS_API_URL = '/subjects'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: '60px'
  },
  {
    title: '学生',
    key: 'studentName',
    width: '120px'
  },
  {
    title: '科目',
    key: 'subjectName',
    width: '120px'
  },
  {
    title: '分数',
    dataIndex: 'score',
    key: 'score',
    width: '80px'
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
  },
  {
    title: '操作',
    key: 'action',
    width: '120px'
  },
]

const grades = ref([])
const students = ref([])
const subjects = ref([])
const loading = ref(false)
const studentsLoading = ref(false)
const subjectsLoading = ref(false)
const modalVisible = ref(false)
const currentRecord = ref(null)
const formRef = ref()
const filterStudentId = ref(undefined)
const filterSubjectId = ref(undefined)

const formState = reactive({
  studentId: undefined,
  subjectId: undefined,
  score: 0,
  remark: ''
})

const rules = {
  studentId: [{ required: true, message: '请选择学生!' }],
  subjectId: [{ required: true, message: '请选择科目!' }],
  score: [{ required: true, message: '请输入分数!' }],
}

// 根据筛选条件过滤成绩列表
const filteredGrades = computed(() => {
  let result = [...grades.value]
  
  if (filterStudentId.value) {
    result = result.filter(item => item.studentId === filterStudentId.value)
  }
  
  if (filterSubjectId.value) {
    result = result.filter(item => item.subjectId === filterSubjectId.value)
  }
  
  return result
})

// 获取学生名称
const getStudentName = (studentId) => {
  const student = students.value.find(item => item.id === studentId)
  return student ? student.name : '未知学生'
}

// 获取科目名称
const getSubjectName = (subjectId) => {
  const subject = subjects.value.find(item => item.id === subjectId)
  return subject ? subject.name : '未知科目'
}

// 根据分数获取颜色
const getScoreColor = (score) => {
  if (score >= 90) return 'green'
  if (score >= 60) return 'blue'
  return 'red'
}

// 处理筛选条件变化
const handleFilterChange = () => {
  // 筛选条件已经通过计算属性自动应用
}

// 显示模态框
const showModal = (record = null) => {
  currentRecord.value = record
  if (record) {
    Object.assign(formState, record)
  } else {
    Object.assign(formState, {
      studentId: undefined,
      subjectId: undefined,
      score: 0,
      remark: ''
    })
  }
  modalVisible.value = true
}

// 处理表单提交
const handleOk = () => {
  formRef.value.validate().then(() => {
    if (currentRecord.value) {
      // 更新成绩
      updateGrade(currentRecord.value.id, formState)
    } else {
      // 创建成绩
      createGrade(formState)
    }
  }).catch(error => {
    console.error('Validation failed:', error)
  })
}

// 处理删除
const handleDelete = (id) => {
  deleteGrade(id)
}

// 获取所有成绩
const fetchGrades = async () => {
  loading.value = true
  try {
    const data = await request.get(API_URL)
    grades.value = data
  } catch (error) {
    console.error('Error fetching grades:', error)
    message.error('获取成绩列表失败')
  } finally {
    loading.value = false
  }
}

// 获取所有学生
const fetchStudents = async () => {
  studentsLoading.value = true
  try {
    const data = await request.get(STUDENTS_API_URL)
    students.value = data
  } catch (error) {
    console.error('Error fetching students:', error)
    message.error('获取学生列表失败')
  } finally {
    studentsLoading.value = false
  }
}

// 获取所有科目
const fetchSubjects = async () => {
  subjectsLoading.value = true
  try {
    const data = await request.get(SUBJECTS_API_URL)
    subjects.value = data
  } catch (error) {
    console.error('Error fetching subjects:', error)
    message.error('获取科目列表失败')
  } finally {
    subjectsLoading.value = false
  }
}

// 创建成绩
const createGrade = async (gradeData) => {
  loading.value = true
  try {
    const data = await request.post(API_URL, gradeData)
    grades.value.push(data)
    message.success('成绩添加成功')
    modalVisible.value = false
  } catch (error) {
    console.error('Error creating grade:', error)
    message.error('成绩添加失败')
  } finally {
    loading.value = false
  }
}

// 更新成绩
const updateGrade = async (id, gradeData) => {
  loading.value = true
  try {
    const data = await request.put(`${API_URL}/${id}`, gradeData)
    const index = grades.value.findIndex(item => item.id === id)
    if (index !== -1) {
      grades.value[index] = data
    }
    message.success('成绩更新成功')
    modalVisible.value = false
  } catch (error) {
    console.error('Error updating grade:', error)
    message.error('成绩更新失败')
  } finally {
    loading.value = false
  }
}

// 删除成绩
const deleteGrade = async (id) => {
  loading.value = true
  try {
    await request.delete(`${API_URL}/${id}`)
    grades.value = grades.value.filter(item => item.id !== id)
    message.success('成绩删除成功')
  } catch (error) {
    console.error('Error deleting grade:', error)
    message.error('成绩删除失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchGrades()
  fetchStudents()
  fetchSubjects()
})
</script>

<style scoped>
.grade-container {
  padding: 24px;
}

.table-operations {
  margin-bottom: 16px;
}
</style>